﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LotteryVote.Entity;
using LotteryVote.Data;
using LotteryVote.Logic.Exceptions;

namespace LotteryVote.Logic
{
    public class MemberPackageFacade
    {
        private MemberPackageDataAccess _daMemberPackage;
        internal MemberPackageDataAccess DaMemberPackage
        {
            get
            {
                if (_daMemberPackage == null)
                    _daMemberPackage = new MemberPackageDataAccess();
                return _daMemberPackage;
            }
            set
            {
                _daMemberPackage = value;
            }
        }

        private CommisionGroupFacade _commGroupFacade;
        public CommisionGroupFacade CommGroupFacade
        {
            get
            {
                if (_commGroupFacade == null)
                    _commGroupFacade = new CommisionGroupFacade();
                return _commGroupFacade;
            }
            set
            {
                _commGroupFacade = value;
            }
        }

        public void AddMemberPackage(User user, int[] groupIds)
        {
            foreach (var groupId in groupIds)
                AddMemberPackage(user, groupId);
        }
        public void AddMemberPackage(User user, int groupId)
        {
            if (user.Role != SystemRole.Guest)
                throw new ApplicationException("非会员不可添加分组!");
            var group = CommGroupFacade.GetCommissionGroup(groupId);
            if (group == null)
                throw new InvalidDataException("group,groupId:" + groupId);
            DaMemberPackage.InsertMemberPackage(user, group);
        }
        public void UpdateMemberPackage(User user, LotterySpeciesEnum speice, int groupId)
        {
            if (user.Role != SystemRole.Guest) return;
            DaMemberPackage.ExecuteWithTransaction(() =>
            {
                DaMemberPackage.DeleteMemberPackage(user, speice);
                CommGroupFacade.DaCommisionGroup.Tandem(DaMemberPackage);
                AddMemberPackage(user, groupId);
            });
        }

        public MemberPackage GetPackage(User user, LotterySpeciesEnum specie)
        {
            return DaMemberPackage.GetMemberPackageBySpecie(user, (int)specie);
        }

    }
}
